package summary;

import java.util.Stack;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 22:17
 */
public class Title404 {

    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int sumOfLeftLeaves(TreeNode root) {
        if (root.left == null && root.right == null) {
            return 0;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = null;
        int sum = 0;
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode pop = stack.pop();
            if (pop.left == null && pop.right == null && pre.left == pop) {
                sum += pop.val;
            }
            pre = pop;
            if (pop.right != null) {
                stack.push(pop.right);
            }
            if (pop.left != null) {
                stack.push(pop.left);
            }
        }
        return sum;
    }

    public int sumOfLeftLeaves1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = sumOfLeftLeaves1(root.left);
        int right = sumOfLeftLeaves1(root.right);
        int middle = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            middle = root.left.val;
        }
        return left + middle + right;
    }

    public static void main(String[] args) {

    }
}
